package com.xlcszsgc.module.resourceimport.ui.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 
 * Title: UpLoadController<br>
 * Description: 接收页面上传的图片,存入项目相应的文件夹中<br>
 * Company: ORCHIS<br>
 * Copyright @ 2011 ORCHIS .All rights reserved.<br>
 * @author RongLT
 * @createDate 2011-11-24
 * @version $Revision: 1.2 $
 */
@Controller
@RequestMapping(value = UpLoadController.modulePath)
public class UpLoadController {
	
	protected final static String modulePath="/UpLoad";
	
	@RequestMapping(value = "/upLoadFile")
	public void getResultReturn(HttpServletRequest request, HttpServletResponse response)throws Exception{
		response.setCharacterEncoding("utf-8");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		String updateFlag=request.getParameter("updateFlag");
		//获取服务器端应用的根路径
		String rootPath=request.getSession().getServletContext().getRealPath("/");
		if(rootPath.contains("/")){
			rootPath+="image/"+updateFlag+"/";
		}else{
			rootPath+="image\\"+updateFlag+"\\";
		}
		
		Map<String,MultipartFile>fileMap=multipartRequest.getFileMap();
		String name = "";
		PrintWriter print=response.getWriter();
		InputStream ins=null;
		OutputStream ops=null;
		try{
			
			for(MultipartFile mf:fileMap.values()){
				CommonsMultipartFile cmf=(CommonsMultipartFile)mf;
				FileItem item =cmf.getFileItem();
				if (!item.isFormField()) {
					name = item.getName();
					if (name == null || name.trim().equals("")) {
						continue;
					}
					
					
					ins=item.getInputStream();
					File file=new File(rootPath+name);
					if(file.exists()){
						file.delete();
					}
					file.createNewFile();//创建要保存的元数据文件，文件名是上传的元数据的文件名
					
					ops=new FileOutputStream(file);
					byte[] b=new byte[1024];
					int count=0;
					while((count=ins.read(b))!=-1){
						ops.write(b, 0, count);
					}
					ops.flush();
					item.delete();//从内从中删除临时文件
					print.print(name+"上传成功");
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			throw e;
		}finally{
			if(ins!=null){
				ins.close();
			}
			if(ops!=null){
				ops.close();
			}
			print.close();
		}
	}
	
}
